define(['jquery', 'bootstrap', 'backend', 'table', 'form', 'vue'], function ($, undefined, Backend, Table, Form, Vue) {

    var prompts = function (money) {
        return new Promise((resolve, reject) => {
            Layer.prompt({
                title: '确认支付金额后提交！',
                formType: 0,
                value: money
            }, function (pass, index) {
                Layer.close(index);
                resolve(pass)
            });
        })
    }

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'booking/order/index' + location.search,
                    add_url: 'booking/order/add',
                    // edit_url: 'booking/order/edit',
                    del_url: 'booking/order/del',
                    table: 'booking_order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [{
                            checkbox: true
                        },
                        {
                            field: 'id',
                            title: __('Id')
                        },
                        {
                            field: 'orderid',
                            title: __('Orderid'),
                            operate: 'LIKE'
                        },  
                        {
                            field: 'storeInfo',
                            title: __('门店')
                            
                        },
                        {
                            field: 'source_id',
                            title: __('Source_id')
                        },
                        {
                            field: 'source.name',
                            title: __('Source'),
                            formatter: Controller.api.content,
                            operate: false
                        },
                        {
                            field: 'user_id',
                            title: __('User_id'),
                            formatter: Table.api.formatter.search
                        },
                        {
                            field: 'user.nickname',
                            title: __('Nickname'),
                            operate: false
                        },
                        {
                            field: 'user_coupon_id',
                            title: __('User_coupon_id')
                        },
                        {
                            field: 'amount',
                            title: __('Amount'),
                            operate: 'BETWEEN'
                        },
                        {
                            field: 'coupon_amount',
                            title: __('Coupon_amount'),
                            operate: 'BETWEEN'
                        },
                        {
                            field: 'payamount',
                            title: __('Payamount'),
                            operate: 'BETWEEN'
                        },
                        {
                            field: 'nums',
                            title: __('Nums')
                        },
                        {
                            field: 'method',
                            title: __('Method'),
                            operate: 'LIKE'
                        },
                        {
                            field: 'paytype',
                            title: __('Paytype'),
                            operate: 'LIKE'
                        },
                        {
                            field: 'paytime',
                            title: __('Paytime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'checkin_time',
                            title: __('Checkin_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'leave_time',
                            title: __('Leave_time'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: {
                                "created": __('Status created'),
                                "paid": __('Status paid'),
                                "expired": __('Status expired'),
                                "checkined": __('Status checkined'),
                                "checkouting": __('Status checkouting'),
                                "canceled": __('Status canceled'),
                                "refunding": __('Status refunding'),
                                "toshopay": __('Status toshopay'),
                                "evaluate": __('Status evaluate'),
                                "finished": __('Status finished')
                            },
                            formatter: Table.api.formatter.status
                        },
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'ip',
                            title: __('Ip'),
                            operate: 'LIKE'
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            width: 120,
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [{
                                name: '订单详情',
                                title: __('订单详情'),
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                text: '订单详情',
                                icon: 'fa fa-sticky-note-o',
                                extend: 'data-area=\'["80%","80%"]\'',
                                url: 'booking/order/detail'
                            }]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        goods: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'booking/order/goods' + location.search,
                    add_url: 'booking/order/add',
                    // edit_url: 'booking/order/edit',
                    del_url: 'booking/order/del',
                    table: 'booking_order',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                fixedColumns: true,
                fixedRightNumber: 1,
                columns: [
                    [{
                            checkbox: true
                        },
                        {
                            field: 'id',
                            title: __('Id')
                        },
                        {
                            field: 'orderid',
                            title: __('Orderid'),
                            operate: 'LIKE'
                        },                       
                        {
                            field: 'user_id',
                            title: __('User_id'),
                            formatter: Table.api.formatter.search
                        },
                        {
                            field: 'user.nickname',
                            title: __('Nickname'),
                            operate: false
                        },
                        // {
                        //     field: 'user_coupon_id',
                        //     title: __('User_coupon_id')
                        // },
                        {
                            field: 'amount',
                            title: __('Amount'),
                            operate: 'BETWEEN'
                        },
                        // {
                        //     field: 'coupon_amount',
                        //     title: __('Coupon_amount'),
                        //     operate: 'BETWEEN'
                        // },
                        {
                            field: 'payamount',
                            title: __('Payamount'),
                            operate: 'BETWEEN'
                        },
                        {
                            field: 'nums',
                            title: __('Nums')
                        },
                        {
                            field: 'method',
                            title: __('Method'),
                            operate: 'LIKE'
                        },
                        {
                            field: 'paytype',
                            title: __('Paytype'),
                            operate: 'LIKE'
                        },
                        {
                            field: 'paytime',
                            title: __('Paytime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },                       
                        {
                            field: 'status',
                            title: __('Status'),
                            searchList: {
                                "created": __('Status created'),
                                "paid": __('Status paid'),
                                "expired": __('Status expired'),
                                "shipped": __('Status shipped'),                               
                                "canceled": __('Status canceled'),
                                "refunding": __('Status refunding'),
                                "toshopay": __('Status toshopay'),
                                "evaluate": __('Status evaluate'),
                                "finished": __('Status finished')
                            },
                            formatter: Table.api.formatter.status
                        },
                        {
                            field: 'createtime',
                            title: __('Createtime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'updatetime',
                            title: __('Updatetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            autocomplete: false,
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'ip',
                            title: __('Ip'),
                            operate: 'LIKE'
                        },
                        {
                            field: 'operate',
                            title: __('Operate'),
                            width: 120,
                            table: table,
                            events: Table.api.events.operate,
                            formatter: Table.api.formatter.operate,
                            buttons: [{
                                name: '订单详情',
                                title: __('订单详情'),
                                classname: 'btn btn-xs btn-primary btn-dialog',
                                text: '订单详情',
                                icon: 'fa fa-sticky-note-o',
                                extend: 'data-area=\'["80%","80%"]\'',
                                url: 'booking/order/goods_detail'
                            }]
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        editAndSave(){
            
            $('.edit-list').delegate('.btn-edit,.btn-cancel,.btn-save', 'click', function () {
                let status = $(this).data('status');
                switch (status) {
                    case 'edit':
                        $(this).nextAll('a').removeClass('hide');
                        $(this).parent().prev().children('div').addClass('hide');
                        $(this).parent().prev().children('input').removeClass('hide');
                        $(this).addClass('hide');
                        break;
                    case 'cancel':
                        $(this).prev().removeClass('hide');
                        $(this).next().addClass('hide');
                        $(this).parent().prev().children('div').removeClass('hide');
                        $(this).parent().prev().children('input').addClass('hide');
                        $(this).addClass('hide');
                        break;
                    case 'save':
                        let val = $(this).parent().prev().children('input').val();
                        let field = $(this).data('field');
                        let id = $(this).data('id');
                        $.post('booking/order/edit_info', {
                            id: id,
                            field: field,
                            value: val
                        }, function (res) {
                            if (res.code == 1) {
                                window.location.reload();
                                Toastr.success(res.msg);
                            } else {
                                Toastr.error(res.msg);
                            }
                        })
                        break;
                }
            })
        },
        detail: function () {
            this.editAndSave();
            

            var checkout = function (row, param) {
                let btn = ['确认退费退房'];
                if (row.paytype != 'system') {
                    btn = ['确认线下退费退房', '确认线上退费'];
                }
                let html = `
                    <div style="padding:15px 15px 0 15px;">
                        <ul class="list-group">
                            <li class="list-group-item">
                                <label class="control-label">共下单：${row.total_day}天</label>
                            </li>
                            <li class="list-group-item">
                                 <label class="control-label">已入住：${row.total_day-row.surplus}天</label>
                            </li>
                            <li class="list-group-item">
                                <label class="control-label">还剩余：${row.surplus}天</label>
                            </li>
                            <li class="list-group-item">
                                <label class="control-label" style="width:73px;">退还费用：</label>
                                <input class="form-control" style="flex:1;" id="out_money" type="number" value="${row.out_money}"/>
                                <span style="margin-left:5px;">元</span>
                            </li>                                                   
                        </ul>      
                    </div>   
                `;
                layer.open({
                    type: 1,
                    skin: 'layui-layer-demo', //样式类名    
                    title: '退费退房确认',
                    anim: 2,
                    area: ['400px', '320px'],
                    shadeClose: true, //开启遮罩关闭
                    content: html,
                    btn: btn,
                    yes: function (index, layero) {
                        param.out_type = 1;//线下退
                        param.out_money = $('#out_money').val();                        
                        $.post('booking/order/edit_info', param, function (res) {
                            if (res.code == 1) {
                                window.location.reload();
                                parent.$(".btn-refresh").trigger("click");
                                Toastr.success(res.msg);
                                Layer.close(index);
                            } else {
                                Toastr.error(res.msg);
                            }
                        })

                    },
                    btn2: function (index, layero) {
                        param.out_type = 2;//线上退
                        param.out_money = $('#out_money').val();   
                        $.post('booking/order/edit_info', param, function (res) {
                            if (res.code == 1) {
                                window.location.reload();
                                parent.$(".btn-refresh").trigger("click");
                                Toastr.success(res.msg);
                                Layer.close(index);
                            } else {
                                Toastr.error(res.msg);
                            }
                        })
                        return false;
                    }
                });
            }

            $('.btn-status-click').click(async function () {
                let value = $(this).data('status');
                let id = $('#order_id').val();
                let now_status = $('#now-status').val();
                let money = 0;
                if (now_status && now_status == 'toshopay' && value == 'checkined') {
                    money = await prompts($('#amount').val());
                }
                let data = {
                    id: id,
                    field: 'status',
                    value: value,
                    amount: money
                };
                $.post('booking/order/edit_info', data, function (res) {
                    if (res.code == 1) {
                        window.location.reload();
                        parent.$(".btn-refresh").trigger("click");
                        Toastr.success(res.msg);
                    } else if (res.data && res.data.paytype) {
                        checkout(res.data, data);
                    } else {
                        Toastr.error(res.msg);
                    }
                })
            })

            $('.btn-save-lodgers').click(function () {
                let lodgers = $('#lodgers').val();
                let id = $('#lodgers').data('id');
                $.post('booking/order/save_lodgers', {
                    lodgers: lodgers,
                    id: id
                }, function (res) {
                    if (res.code == 1) {
                        window.location.reload();
                        Toastr.success(res.msg);
                    } else {
                        Toastr.error(res.msg);
                    }
                })
            })
            $(document).on("fa.event.appendfieldlist", ".panel-fieldlist .btn-append", function (e, obj) {
                console.log(8)
                Form.events.selectpicker(obj);
            });
            Form.events.fieldlist($('.panel-fieldlist'));
            Form.events.datetimepicker($('.edit-list'));
            Controller.api.bindevent();
        },
        goods_detail(){
            
            this.editAndSave();

            $('.btn-status-click').click(async function () {
                let value = $(this).data('status');
                let id = $('#order_id').val();
                let now_status = $('#now-status').val();
                let money = 0;
                if (now_status && now_status == 'toshopay' && value == 'checkined') {
                    money = await prompts($('#amount').val());
                }
                let data = {
                    id: id,
                    field: 'status',
                    value: value,
                    amount: money
                };
                $.post('booking/order/edit_info', data, function (res) {
                    if (res.code == 1) {
                        window.location.reload();
                        parent.$(".btn-refresh").trigger("click");
                        Toastr.success(res.msg);
                    } else if (res.data && res.data.paytype) {
                       
                    } else {
                        Toastr.error(res.msg);
                    }
                })
            })

            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            content: function (value, row, index) {
                var width = this.width != undefined ? (this.width.match(/^\d+$/) ? this.width + "px" : this.width) : "250px";
                return "<div style='white-space: nowrap; text-overflow:ellipsis; overflow: hidden; max-width:" + width + ";' title='" + value + "' data-toggle='tooltip' data-placement='right'>" + value + "</div>";
            },
        }
    };
    return Controller;
});